import { useState } from 'react'
import { BasicModalProps } from '../index.type'

export default function useModal(): [
  BasicModalProps['register'],
  { openModal: (values?: any) => void; closeModal: () => void }
] {
  const [visible, setVisible] = useState(false)
  const [initialValues, setInitialValues] = useState<any>()

  function openModal(initialValues?: any) {
    setInitialValues(initialValues)
    setVisible(true)
  }

  function closeModal() {
    setVisible(false)
  }

  function register(callback: (initialValues: any) => void) {
    visible && callback?.(initialValues)
    return { visible, initialValues, onClose: closeModal }
  }

  const modalActions = {
    openModal,
    closeModal
  }

  return [register, modalActions]
}
